!function () {
    layui.config({base: '/layui/lay/modules/'}).use(['table', 'laydate', 'dateformat','upload', 'form','common'], function () {
        //定义
        var $ = layui.jquery,
            table = layui.table,
            form = layui.form,
            upload = layui.upload,
            dateformat = layui.dateformat,
            laydate = layui.laydate,
            common = layui.common;//自定义模块

        //富文本编辑器
        //var E = window.wangEditor;
        //定义总变量
        var ProductTag = {
            tableId: "productTagTable",    //表格id
            productTagType:{'':'全部'},              //父菜单节点
            condition: {                //查询条件
                name: "",
                type:"",
                startDate: "",
                endDate: ""
            },
            //editor :new E('#ProductTagText') //富文本内容
        }

        var uploadFileBtn = upload.render({
            elem: '#uploadBtn'
            ,url: '/upload/uploadFiles'
            ,field:"layuiFiles"
            ,accept: 'file' //普通文件
            ,auto: false    //不自动上传
            ,exts: 'jpg|png|jpeg' //只允许上传压缩文件
            ,choose: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    var $uploadListDiv = $('#uploadListDiv');
                    var htmlDiv ='';
                    if(file.type.indexOf("image") !=-1){
                        if( (file.size/1014).toFixed(1) > 10240 ){
                            return layer.msg("图片不能超过10M");
                            return false;
                        }
                        //限制图片尺寸
                        var img = new Image();

                        var flagUpload = true;
                        img.onload = function(){
                            if(img.width != 1920 || img.height != 780){
                                layer.msg("资讯图片固定尺寸为1920*780");
                                flagUpload= false;
                            }
                            uploadFileBtn.config.data ={"dir":"image"};
                            htmlDiv +='<img class="fileDiv" style="height: 137px;width: 137px;"/>';
                            if( flagUpload ){
                                $uploadListDiv.empty().append(htmlDiv);
                                //执行上传
                                obj.upload(index, file);
                            }
                        };
                        img.src = result;
                    }
                });
            }
            ,done: function(res){
                if(res.code==1){
                    layer.alert(res.message,5);
                }
                if(res.error>0){
                    return layer.msg(res.message);
                }
                if(res.error==0){
                    var $uploadListDiv = $('#uploadListDiv');
                    $("#tagUrl").val(res.url);
                    $uploadListDiv.find(".fileDiv").attr("src",res.url);
                    layer.msg("上传成功");
                }
            }
        });

        /**
         * 初始化列表列
         * **/
        ProductTag.initColumn = function(){
            return [[
                /*{type: 'checkbox', fixed: 'left'},*/
                {field: 'id', title: 'ID', width: 80,hide:true},
                {field: 'name', title: '标签名称', width: 160},
                {field: 'tagUrl', title: '标签图片', width: 260,templet: '#imgRender'},
                {field: 'remark', title: '标签描述', width: 260},
                {field: 'type' ,title :'标签类别',width:120,templet:function(row){
                    return common.codeItem[row.type];
                    }},
                {field: 'createTime' ,title :'创建时间',width: 165, templet: function (row) {
                        return dateformat.format(common.NewDate(row.createTime), 'yyyy-MM-dd');
                    }},
                {field: 'createPerson' ,title :'创建人',width:120},
                {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 280, align: 'center'}
            ]];
        }

        /***
         * 初始化字典信息
         */
        ProductTag.initDict = function(){

        }


        /**
         * 查询方法
         * **/
        ProductTag.search = function(){
            var queryData = {};
            queryData["name"] = $("#name").val();
            queryData["type"] = $("#typeQuery").val();
            queryData["startDate"] = $("#startDate").val();
            queryData["endDate"] = $("#endDate").val();
            table.reload(ProductTag.tableId, {where: queryData,page: {curr: 1}});
        }

        /**
         * 新增记录
         * **/
        ProductTag.addRecord =function (){

            //初始化表单
            $('#editForm')[0].reset();
            $('#editForm :input').val("");//重置所有的input
            common.initOptions('#type','type');//根据菜单构建下拉列表
            //打开弹出层
            layer.open({
                type: 1, maxmin: true, title: '新增标签', shade: 0.4, shadeClose: false,
                area: ['640px', '600px'], content: $('#editForm').show(), btn: ['保存', '取消'],
                yes: function () {
                    $('#saveRecord').click();
                }, btn2: function () {
                    layer.closeAll();
                }, end: function () {
                    $('#editForm').hide();
                }
            });
        }

        /**
         * 修改记录
         * **/
        ProductTag.editRecord =function (data){
            //初始化数据
            $("#uploadListDiv").empty();
            $.ajax({
                async: false,
                url: '/tag/findProductTag?id=' + data.id,
                success: function (result) {
                    if (result && result.code == 200) {
                        var data = result.data;
                        //初始化表单
                        common.initOptions('#type','type');
                        form.render('radio').val('editForm', data);
                        $("#uploadListDiv").append('<img class="fileDiv" style="height: 137px;width: 137px;"/>');
                        $("#uploadListDiv").find(".fileDiv").attr("src",data.tagUrl);
                        //打开弹出层
                        layer.open({
                            type: 1, maxmin: true, title: '修改标签', shade: 0.4, shadeClose: false,
                            area: ['640px', '600px'], content: $('#editForm').show(), btn: ['保存', '取消'],
                            yes: function () {
                                $('#saveRecord').click();
                            }, btn2: function () {
                                layer.closeAll();
                            }, end: function () {
                                $('#editForm').hide();
                            }
                        });
                    }else
                        layer.alert(result.msg || '请求失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        }

        /**
         * 删除记录
         * **/
        ProductTag.deleteRecord =function (data){
            $.ajax({
                async: false,
                type: 'post',
                url: '/tag/delete?id=' + data.id,
                success: function (result) {
                    if (result && result.code == 200) {
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        ProductTag.search();
                    }
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        }


        //调用公共js渲染select下拉框
        common.initOptions('#typeQuery','type');
        //初始化渲染列表
        //日期
        var startDate = laydate.render({
            elem: '#startDate',
            done: function(value, date){
                endDate.config.min = date;
                endDate.config.min.month = date.month -1;
            }
        });
        var endDate =  laydate.render({
            elem: '#endDate',
            done: function(value, date){
                if($.trim(value) == ''){
                    var curDate = new Date();
                    date = {'date': curDate.getDate(), 'month': curDate.getMonth()+1, 'year': curDate.getFullYear()};
                }
                startDate.config.max = date;
                startDate.config.max.month = date.month -1;
            }
        });

        table.render({
            elem:"#productTagTable"
            ,url:"/tag/listPage"
            ,cellMinWidth:80
            ,request: {pageName: 'pageNum', limitName: 'pageSize'}
            ,page: true
            ,cols:ProductTag.initColumn(),
            cellMinHeight:200

        });

        // 搜索按钮点击事件
        $('#btnSearch').click(function () {
            ProductTag.search();
        });

        // 重置点击事件
        $('#resetSearch').click(function () {
            $('#queryTools input').val('');
            $('#queryTools select').val('');
            ProductTag.search();
        });

        // 添加按钮点击事件
        $('#btnAdd').click(function () {
            ProductTag.addRecord();
        });

        //自定义验证规则
        form.verify({
            tagLen: [
                /^[\d\D]{0,16}$/
                ,'标签名称最多输入16个字'
            ],
            textLen:[
                /^[\d\D]{0,200}$/
                ,'最多输入200个字符'
            ],
        });

        //监听工具条
        table.on('tool(' + ProductTag.tableId + ')',function(obj){
            var data = obj.data;
            var layEvent = obj.event;
            if( layEvent ==='detail'){
                //查看
                return false;
            } else if( layEvent ==='del'){
                layer.confirm('确定要删除该标签吗？', function (index) {
                    ProductTag.deleteRecord(data);
                    return false;
                });
            } else if( layEvent ==='edit'){
                ProductTag.editRecord(data);
                return false;
            }
        });

        //监听提交事件
        form.on('submit(editRecord)',function(data){

            //通过from提交  包含图片
            var formdata  = new FormData(data.form);
            var postUrl = !data.field['id'] ? '/tag/addProductTag' : '/tag/editProductTag';

            $.ajax({
                async: false, type: 'post', traditional: true, data: formdata, url: postUrl,
                contentType:false,processData:false,
                success: function (data) {
                    if (data && data.code == 200) {
                        layer.closeAll();
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        ProductTag.search();
                    } else
                        layer.alert(data.msg || '操作失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.closeAll();
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
            return false;
        });

    });
}();